import {
  Component,
  OnInit,
  OnChanges,
  Output,
  Input,
  EventEmitter,
  ViewChild,
  AfterViewInit,
  ElementRef,
  SimpleChanges,
  ViewContainerRef
} from '@angular/core';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { fromEvent } from 'rxjs';
import { debounceTime, pluck, distinctUntilChanged } from 'rxjs/operators';
import { isEmptyObject } from '@utils/tool';
import { WyySearchPanelComponent } from './wyy-search-panel/wyy-search-panel.component';
import { SearchResult } from '@services/data-types/common.type';
import { User } from '@services/data-types/member.type';


@Component({
  selector: 'app-wyy-search',
  templateUrl: './wyy-search.component.html',
  styleUrls: ['./wyy-search.component.less']
})
export class WyySearchComponent implements OnInit, AfterViewInit, OnChanges {
  user: User;
  private overlayRef: OverlayRef;
  @Input() searchResult: SearchResult;
  @Input() connectedRef: ElementRef;
  @Output() onSearch = new EventEmitter<string>();
  @ViewChild('inputEle', { static: false }) private nzInput: ElementRef;
  @ViewChild('search', { static: false }) private searchResultRef: ElementRef;
  constructor(
    private viewContainerRef: ViewContainerRef,
    private overlay: Overlay
  ) { }

  ngOnInit() {}
  ngOnChanges(changes: SimpleChanges) {
    if (changes.searchResult && !changes.searchResult.firstChange) {
      if (!isEmptyObject(changes.searchResult)) {
        this.showOverlayPanel();
      } else {
        this.hideOverlayPanel();
      }
    }
  }
  ngAfterViewInit() {
    fromEvent(this.nzInput.nativeElement, 'input')
    .pipe(debounceTime(300), distinctUntilChanged(), pluck('target', 'value'))
    .subscribe((value: string) => {
      const needValue = value.trim();
      this.onSearch.emit(needValue);
    });
  }
  onFocus() {
    if (this.searchResult && !isEmptyObject(this.searchResult)) {
      this.showOverlayPanel();
    }
  }
  onBlur() {
    this.hideOverlayPanel();
  }
  showOverlayPanel() {
    this.hideOverlayPanel();
    const positionStrategy = this.overlay.position()
      .flexibleConnectedTo(this.connectedRef || this.searchResultRef)
      .withPositions([
        {
          originX: 'start',
          originY: 'bottom',
          overlayX: 'start',
          overlayY: 'top'
        }
      ]).withLockedPosition(true);
    this.overlayRef = this.overlay.create({
      hasBackdrop: true,
      positionStrategy,
      scrollStrategy: this.overlay.scrollStrategies.reposition()
    });
    const panelPortal = new ComponentPortal(WyySearchPanelComponent, this.viewContainerRef);
    const panelRef = this.overlayRef.attach(panelPortal);
    panelRef.instance.searchResult = this.searchResult;
    this.overlayRef.backdropClick().subscribe(() => {
      this.hideOverlayPanel();
    });
  }
  hideOverlayPanel() {
    if (this.overlayRef && this.overlayRef.hasAttached) {
      this.overlayRef.dispose();
    }
  }
}
